﻿using System.Web.Mvc;
using System.Web;
using System;
using System.Web.Routing;
using Liber;
using Liber.WEB;
using Liber.API;
using SoBusiness.API;
using System.Timers;
using SoBusiness.Controllers;

namespace SoBusiness
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            XMLSetting.SetDefault(Server.MapPath("")+"\\NodeConfig.cfg");
            if (XMLSetting.DefaultSetting.First("Host").Property("mode", "inproc") == "inproc")
            {
                LiberController.API = new SoBizAPI();
            }
            else
            {
                LiberController.API = new RemoteAPI();
            }


            AreaRegistration.RegisterAllAreas();
            GlobalFilters.Filters.Add(new AuthorFilter());
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            var n = XMLSetting.DefaultSetting.First("SyncFromOpenApp").First("Default").Value;
            if (!string.IsNullOrEmpty(n))
            {
                var url = XMLSetting.DefaultSetting.First("SyncFromOpenApp").Find("Name", n).Value;
                if (!string.IsNullOrEmpty(url))
                {
                    Timer syncOpenDataRobot = new Timer(60000);
                    syncOpenDataRobot.Elapsed += syncOpenData;
                    syncOpenDataRobot.Start();
                }
            }


            Timer checkWxMsgRobot = new Timer(30000);
            checkWxMsgRobot.Elapsed += CheckWxMsg;
            checkWxMsgRobot.Start();
        }

        private void CheckWxMsg(object sender, ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour > 22 || DateTime.Now.Hour < 5)
            {
                //每天22点到凌晨5点之间不同步
                return;
            }
            TLB2BController.CheckMessage();
        }

        private void syncOpenData(object sender, ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour > 22 || DateTime.Now.Hour < 5)
            {
                //每天22点到凌晨5点之间不同步
                return;
            }
            var n = XMLSetting.DefaultSetting.First("SyncFromOpenApp").First("Default").Value;
            if (!string.IsNullOrEmpty(n))
            {
                var url = XMLSetting.DefaultSetting.First("SyncFromOpenApp").Find("Name", n).Value;
                if (!string.IsNullOrEmpty(url))
                {
                    WebHelper.BeginGetFrom(null, url);
                }
            }
        }
    }
}